package MyArrayStack;

import java.util.Arrays;

//数组栈

public class MyStack {
    public int usedSize;
    public int[] elem;

    public MyStack() {
        this.elem = new int[10];
    }

    public void push(int data){
        if (isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize++] = data;
    }

    public boolean isFull(){
        return this.usedSize == elem.length;
    }

    public int pop() throws EmptyStackException{
        if(isEmpty()){
            throw new EmptyStackException("栈为空，无法弹栈!");
        }
        int val = elem[usedSize-1];
        this.usedSize--;
        return val;
    }

    public int peek() throws EmptyStackException{
        if(isEmpty()){
            throw new EmptyStackException("栈为空，无法取栈顶元素!");
        }
        return elem[usedSize-1];
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    public void display(){
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }
}
